﻿namespace Macds.Core.Task
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Timers;

    public abstract class TaskElement
    {
        #region Properties

        public Timer TimerInternal { get; set; }
        public event TaskElementEventHandler OnTimerElapsed;
        public bool Active 
        { 
            get 
            { 
                return TimerInternal == null ? false : TimerInternal.Enabled; 
            } 
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Start the timer process
        /// </summary>
        public void Start()
        {
            if (TimerInternal != null)
                TimerInternal.Start();
        }

        /// <summary>
        /// Stop the timer process
        /// </summary>
        public void Stop()
        {
            if (TimerInternal != null)
                TimerInternal.Stop();
        }

        /// <summary>
        /// Send an manual OnTimerElapsed event
        /// </summary>
        public void SendOnTimerElapsed()
        {
            if (OnTimerElapsed != null)
                OnTimerElapsed(this);
        }

        /// <summary>
        /// If the instance is null, it is created. Otherwise the timer is stopped and the interval added.
        /// The timer is not started.
        /// </summary>
        /// <param name="interval">milliseconds</param>
        public void SetTimer(double interval)
        {
            if (TimerInternal == null)
            {
                TimerInternal = new Timer();
                TimerInternal.Elapsed += new ElapsedEventHandler(TimerInternalElapsed);
            }

            if (TimerInternal.Enabled)
                TimerInternal.Stop();

            TimerInternal.Interval = interval;
        }

        /// <summary>
        /// If the current instance require a previous validation
        /// before it is used by the event returned, that logic must be added here.
        /// Otherwise just override it without logic.
        /// </summary>
        public abstract void ProcessInternalTask();

        #endregion

        #region Private Methods

        private void TimerInternalElapsed(object sender, EventArgs arg)
        {
            Stop();
            ProcessInternalTask();
            SendOnTimerElapsed();
        }

        #endregion
    }
}
